import json
# 独立使用django的model
import sys
import os

pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd + "../")
# 找到根目录（与工程名一样的文件夹）下的settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject8.settings')

import django

django.setup()

from china_regions.models import Country, Province, City, Town


def insert():
    with open("../json/province.json", 'r', encoding='utf-8')as a:
        with open("../json/city.json", 'r', encoding='utf-8')as b:
            with open("../json/county.json", 'r', encoding='utf-8')as c:
                with open("../json/town.json", 'r', encoding='utf-8') as g:
                    d = json.load(a)
                    e = json.load(b)
                    f = json.load(c)
                    h = json.load(g)
                    for d1 in d:
                        province = Province()
                        province.name = d1['name']
                        province.province_id = d1['id']
                        province.save()
                        try:
                            for d2 in e[d1['id']]:
                                city = City()
                                city.name = d2['name']
                                city.city_id = d2['id']
                                city.province = province
                                city.save()
                                try:
                                    for d3 in f[d2['id']]:
                                        country = Country()
                                        country.name = d3['name']
                                        country.country_id = d3['id']
                                        country.city = city
                                        country.save()
                                        try:
                                            for d4 in h[d3['id']]:
                                                town = Town()
                                                town.name = d4['name']
                                                town.town_id = d4['id']
                                                town.country = country
                                                town.save()
                                        except:
                                            continue
                                        else:
                                            print(11)
                                except:
                                    continue
                                else:
                                    print(111)
                        except:
                            continue
                        else:
                            print(11)
                    g.close()
            c.close()
        b.close()
    a.close()


if __name__ == '__main__':
    insert()
